## ** 统一的后端 响应格式 author：zhaomin ** ### 

from fastapi.responses import JSONResponse
from typing import Optional, Any

from app.schemas.base.request import SuccessResponse, FailedResponse
from app.utils.app_log import logger



# 固定响应格式 
class RequestHandler:
    """
    前后端交互处理类。
    提供统一的请求解析、响应生成和异常处理功能。
    """

    @staticmethod
    def create_response(
        data: Any = None,
        code: int = 200,
        message: str = "Success",
        remarks: Optional[str] = None
    ) -> JSONResponse:
        """创建统一的成功响应。"""
        return JSONResponse(
            content=SuccessResponse(
                code=code,
                message=message,
                remarks=remarks,
                data=data
            ).model_dump()
        )

    @staticmethod
    def success(
        data: Any = None,
        message: str = "操作成功",
        remarks: Optional[str] = None
    ) -> JSONResponse:
        """创建成功响应的快捷方法。"""
        return RequestHandler.create_response(
            data=data,
            code=200,
            message=message,
            remarks=remarks
        )

    @staticmethod
    def created(
        data: Any = None,
        message: str = "创建成功",
        remarks: Optional[str] = None
    ) -> JSONResponse:
        """创建201状态码响应。"""
        return RequestHandler.create_response(
            data=data,
            code=201,
            message=message,
            remarks=remarks
        )

    @staticmethod
    def error(
        message: str = "操作失败",
        code: int = 400,
        remarks: Optional[str] = None,
        data: Any = None
    ) -> JSONResponse:
        """创建错误响应。"""
        return JSONResponse(
            status_code=code,
            content=FailedResponse(
                code=code,
                message=message,
                remarks=remarks,
                data=data
            ).model_dump()
        )

    @staticmethod
    def unauthorized(
        message: str = "未授权访问",
        remarks: Optional[str] = None
    ) -> JSONResponse:
        """创建401未授权响应。"""
        return RequestHandler.error(
            message=message,
            code=401,
            remarks=remarks
        )

    @staticmethod
    def forbidden(
        message: str = "权限不足",
        remarks: Optional[str] = None
    ) -> JSONResponse:
        """创建403禁止访问响应。"""
        return RequestHandler.error(
            message=message,
            code=403,
            remarks=remarks
        )

    @staticmethod
    def not_found(
        message: str = "资源不存在",
        remarks: Optional[str] = None
    ) -> JSONResponse:
        """创建404未找到响应。"""
        return RequestHandler.error(
            message=message,
            code=404,
            remarks=remarks
        )

    @staticmethod
    def validation_error(
        message: str = "数据验证失败",
        errors: Any = None,
        remarks: Optional[str] = None
    ) -> JSONResponse:
        """创建422数据验证错误响应。"""
        return RequestHandler.error(
            message=message,
            code=422,
            remarks=remarks,
            data=errors
        )

    @staticmethod
    def server_error(
        message: str = "服务器内部错误",
        remarks: Optional[str] = "请稍后重试或联系管理员"
    ) -> JSONResponse:
        """创建500服务器错误响应。"""
        return RequestHandler.error(
            message=message,
            code=500,
            remarks=remarks
        )

    @staticmethod
    def handle_exception(e: Exception) -> JSONResponse:
        """统一处理异常并返回标准错误响应。"""
        logger.error(f"Unhandled exception: {str(e)}")
        return RequestHandler.server_error(
            message="发生未预期的错误",
            remarks=f"错误详情：{str(e)}"
        )

